#include <gflags/gflags.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
#include <string.h>
#include <pthread.h>
#include <thread>
#include <string>
#include <boost/tokenizer.hpp>
#include <zeroplusmq.h>

using namespace zeroplus::mq;

DEFINE_string(uri, "tcp://127.0.0.1:63790:63291:6279", "URI in the format tcp://host:namesrvPort:brokerPort:redisPort");
DEFINE_int32(brokerId, 0, "brokerId, Master or Slave");

std::tuple<std::string, std::string, std::string> ReMakeFlagUri(std::string const &uri)
{
    // 使用 Boost.Tokenizer 按 ':' 分割字符串
    boost::char_separator<char> sep(":");
    boost::tokenizer<boost::char_separator<char>> tokens(uri, sep);
    // 存储解析后的部分
    std::vector<std::string> parts;
    for (const auto &t : tokens)
    {
        parts.push_back(t);
    }
    // 验证解析结果
    if (parts.size() != 5 || parts[0] != "tcp" || parts[1] != "//127.0.0.1")
    {
        LOG_ERROR("%d %s %s", parts.size(), parts[0].c_str(), parts[1].c_str());
        LOG_FATAL("Invalid URI format. Expected format: tcp://127.0.0.1:namesrvPort:brokerPort:redisPort");
    }
    // 构建最终的 URI
    std::string namesrvUri = parts[0] + ":" + parts[1] + ":" + parts[2];
    std::string brokerUri = parts[0] + ":" + parts[1] + ":" + parts[3];
    std::string redisUri = parts[0] + ":" + parts[1] + ":" + parts[4];
    return std::make_tuple(namesrvUri, brokerUri, redisUri);
}

int main(int argc, char **argv)
{
    gflags::ParseCommandLineFlags(&argc, &argv, true);
    auto [namesrvUri, brokerUri, redisUri] = ReMakeFlagUri(FLAGS_uri);
    std::map<std::string, std::string> uriMap;
    uriMap["namesrvAddr"] = namesrvUri;
    uriMap["brokerAddr"] = brokerUri;
    uriMap["redisAddr"] = redisUri;
    BrokerController broker(uriMap, FLAGS_brokerId);
    broker.Start();
}
